package com.blb.socket.demo3;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;

/**
 * 文件客户端
 */
public class FileClient {

    /**
     * 发送文件
     * @param ip
     * @param port
     * @param path
     */
    public void sendFile(String ip,int port,String path){
        //创建Socket
        //创建输出流
        try (Socket socket = new Socket(ip,port);
             ObjectOutputStream os = new ObjectOutputStream(socket.getOutputStream())){
            File file = new File(path);
            if(!file.exists()){
                System.out.println(path+"不存在");
                return;
            }
            //发送文件名
            os.writeUTF(file.getName());
            os.flush();
            //创建文件输入流
            FileInputStream fis = new FileInputStream(file);
            byte[] buf = new byte[1024];
            int len = 0;
            //读取本地文件字节
            while((len = fis.read(buf)) != -1){
                //发送到网络中
                os.write(buf,0,len);
            }
            os.flush();
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new FileClient().sendFile("192.168.1.104",8888,"D:\\install\\apache-jmeter-5.4.1.zip");
    }
}
